#!/usr/bin/python
# -*- coding: utf-8 -*-

from twisted.internet import reactor
from twisted.web.client import getPage
import cairo
import os
import gtk

#temporary, remove later
DIR_USER	= os.environ['HOME'] + '/.feedbar'
DIR_IMG	= os.environ['HOME'] + '/.feedbar/images/'
DIR_TMP	= '/tmp/feedbar/'
if not os.path.isdir(DIR_TMP):
    os.mkdir(DIR_TMP)


def getlogo(url, height):
    filename = os.path.basename(url)
    agent = getPage(url)
    agent.addCallback(saveImg, filename, height)
    agent.addErrback(errorHandler)


def saveImg(data, name, height):
    tempfile = DIR_TMP + name
    basename, extension = os.path.splitext(name)
    open(tempfile, 'wb').write(data)
    if not extension == ".png":
        pixbuf = gtk.gdk.pixbuf_new_from_file(tempfile)
        os.remove(tempfile)
        tempfile = DIR_TMP + basename + ".png"
        name = basename + ".png"
        pixbuf.save(tempfile, "png")
    scaleImg(tempfile, name, height)

def scaleImg(tempfile, name, height):
#    print tempfile
    source = cairo.ImageSurface.create_from_png(tempfile)
    logo_height = source.get_height()
    logo_width = source.get_width()

    new_height = height * 0.8
    measure = new_height / logo_height
    new_width = logo_width * measure

    surface = cairo.ImageSurface(source.get_format(), int(new_width), int(new_height))
    cr = cairo.Context(surface)

    cr.scale(measure, measure)
    cr.set_source_surface (source, 0, 0)
    cr.paint()


    surface.write_to_png(DIR_IMG + name)
    os.remove(tempfile)

def errorHandler(failure):
    """Error Handling"""
    print "problem"
